package com.stark.commons.spring.core.boot.properties;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;

import com.stark.commons.spring.core.util.Utils;

import lombok.Data;

/**
 * <code>Elasticsearch</code> 整合 <code>X-Pack</code> 配置项。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
@ConfigurationProperties(prefix = "spring.data.elasticsearch")
@Data
public class XPackElasticsearchProperties {

	/** 集群名称 */
	private String clusterName = "elasticsearch";

	/** 集群节点列表， {host:port} 以 "," 隔开 */
	private String clusterNodes;
	
	/** 自动发现集群节点 */
	private boolean clientTransportSniff = true;
	
	/** 不校验集群名称 */
	private boolean clientIgnoreClusterName = false;
	
	/** 连接超时时间 */
	private String clientPingTimeout = "5s";
	
	/** 心跳检测间隔时间 */
	private String clientNodesSamplerInterval = "5s";
	
	/** X-Pack 配置项，仅支持 PKCS#12 格式证书 */
	private XPackProperties xpack = new XPackProperties();
	
	/**
	 * X-Pack 配置项。
	 * @author Ben
	 * @since 1.0.0
	 * @version 1.0.0
	 */
	@Data
	public static class XPackProperties {
		
		/** 临时文件目录 */
		private String tmpDir = "java.io.tmpdir";
		
		/** 用户名 */
		private String securityUser;
		
		/** 密码 */
		private String securityPassword;
		
		/** 是否启用 SSL */
		private boolean securityTransportSslEnabled = true;
		
		/** SSL 校验模式，默认 certificate */
	    private String sslVerificationMode = "certificate";
	    
	    /** 秘钥存储文件路径 */
	    private String sslKeystorePath;
	    
	    /** 证书存储文件路径 */
	    private String sslTruststorePath;
	    
	    /** 密码存储文件密码 */
	    private String sslKeystorePassword;
	    
	    /** 证书存储文件密码 */
	    private String sslTruststorePassword;
	    
	    public Map<String, Object> createProperties() throws IOException {
	    	Map<String, Object> properties = new HashMap<>();
	    	properties.put("xpack.security.user", StringUtils.defaultString(securityUser) + ":" + StringUtils.defaultString(securityPassword));
	    	properties.put("xpack.security.transport.ssl.enabled", securityTransportSslEnabled);
	    	putProperty(properties, "xpack.ssl.verification_mode", sslVerificationMode);
	    	putProperty(properties, "xpack.ssl.keystore.path", Utils.classpath2disk(tmpDir, sslKeystorePath));
	    	putProperty(properties, "xpack.ssl.truststore.path", Utils.classpath2disk(tmpDir, sslTruststorePath));
	    	putProperty(properties, "xpack.ssl.keystore.password", sslKeystorePassword);
	    	putProperty(properties, "xpack.ssl.truststore.password", sslTruststorePassword);
	    	return properties;
	    }
	    
	    private void putProperty(Map<String, Object> properties, String key, Object value) {
	    	if (value != null) {
	    		properties.put(key, value);
	    	}
	    }
	    
	}
	
}
